package com.heitian.ssm.controller;

import cc.openkit.common.KitUtil;
import com.alibaba.fastjson.JSONObject;
import com.heitian.ssm.model.AddressList;
import com.heitian.ssm.service.AddressListService;
import com.heitian.ssm.service.RecentContactsService;
import com.heitian.ssm.util.Pager;
import com.heitian.ssm.util.StaticFinalVar;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.*;

@Controller
@RequestMapping("/addressList")
public class AddressListController {
    private Logger log = Logger.getLogger(AddressListController.class);
    @Resource
    private AddressListService addressListService;
    @Resource
    private RecentContactsService recentContactsService;
    @Autowired
    private ServletContext servletContext;

    @RequestMapping("/show")
    public ModelAndView show(HttpServletRequest request) {
        //log.info("查询所有用户信息");
        //List<AddressList> list = addressListService.selectAll();

        ModelAndView mv = new ModelAndView();
        mv.setViewName("addressList/list");
        //mv.addObject("list",list);
        return mv;
    }

    @RequestMapping("/getAllJson")
    @ResponseBody
    public Object getAllJson(HttpServletRequest request) {
        log.info("获取通讯录数据");
        String search = request.getParameter("search");
        String page = request.getParameter("page");
        String limit = request.getParameter("limit");

        Pager pager = null;
        if (KitUtil.feikong(page) && KitUtil.feikong(limit)) {
            pager = new Pager(Integer.parseInt(page), Integer.parseInt(limit));
        }

        List<AddressList> list = addressListService.selectBySearch(search, pager);

        int count = 0;
        if (list != null) {
            count = addressListService.getCount(search);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        // 返回数据
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", count);
        map.put("data", list);

        return JSONObject.toJSON(map);
    }

    @RequestMapping("/getJson")
    @ResponseBody
    public Object getJson(HttpServletRequest request) {
        log.info("获取通讯录数据");
        String search = request.getParameter("search");

        List<AddressList> list = addressListService.selectAllAddressList(search);

        Map<String, Object> map = new HashMap<String, Object>();
        // 返回数据
        map.put("code", 0);
        map.put("msg", "");
        map.put("data", list);

        return JSONObject.toJSON(map);
    }

    /**
     * 去添加页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/goAdd", method = RequestMethod.GET)
    public Object goAdd(HttpServletRequest request) {
        log.info("通讯录 》 添加 》 跳转");
        //查询出所有的分类 给某个分类进行添加通讯录
        ModelAndView mv = new ModelAndView();
        mv.setViewName("addressList/add");
        return mv;
    }

    /**
     * 修改前的查询
     *
     * @param request
     * @return
     * @throws Exception //
     */
    @RequestMapping(value = "/goUpdate", method = RequestMethod.GET)
    public ModelAndView goUpdate(HttpServletRequest request) throws Exception {
        log.info("通讯录管理 》 修改 》 跳转");
        String id = request.getParameter("id");
        AddressList modelById = addressListService.findModelById(id);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("addressList/update");
        mv.addObject("kitModel", modelById);
        return mv;
    }

    /**
     * 修改前的查询
     *
     * @param request
     * @return
     * @throws Exception //
     */
    @RequestMapping(value = "/goImport", method = RequestMethod.GET)
    public ModelAndView goImport(HttpServletRequest request) throws Exception {
        log.info("通讯录管理 》 导入 》 跳转");
        String id = request.getParameter("id");
        AddressList modelById = addressListService.findModelById(id);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("addressList/import");
        mv.addObject("kitModel", modelById);
        return mv;
    }

    /**
     * 添加
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Object add(HttpServletRequest request) {
        log.info("通讯录 》 添加 》 保存");
        String name = request.getParameter("name");//姓名
        String group = request.getParameter("group");//部门
        String imgUrl = request.getParameter("imgUrl");//图片url
        String loginId = request.getParameter("loginId");//工号
        String place = request.getParameter("place");//分机号
        String area = request.getParameter("area");//所在地

        AddressList addressList = new AddressList();
        if (name != null && !"".equals(name)) {
            addressList.setName(name);
        }
        if (group != null && !"".equals(group)) {
            addressList.setGroup(group);
        }
        if (imgUrl != null && !"".equals(imgUrl)) {
            addressList.setImgUrl(imgUrl);
        }
        if (loginId != null && !"".equals(loginId)) {
            addressList.setLoginId(loginId);
        }
        if (place != null && !"".equals(place)) {
            addressList.setPlace(place);
        }
        if (area != null && !"".equals(area)) {
            addressList.setArea(Integer.parseInt(area));
        }
        addressList.setId(KitUtil.uuid());
        addressList.setCreateTime(new Date());
        return JSONObject.toJSON(addressListService.save(addressList) == 1 ? KitUtil.returnMap("200", StaticFinalVar.ADD_OK) : KitUtil.returnMap("101", StaticFinalVar.ADD_ERR));
    }

    /**
     * 修改
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(HttpServletRequest request) {
        log.info("通讯录 》 修改 》 保存");
        String id = request.getParameter("id");//id
        String name = request.getParameter("name");//姓名
        String group = request.getParameter("group");//部门
        String imgUrl = request.getParameter("imgUrl");//图片url
        String loginId = request.getParameter("loginId");//工号
        String place = request.getParameter("place");//分机号
        String area = request.getParameter("area");//所在地

        AddressList addressList = new AddressList();
        if (name != null && !"".equals(name)) {
            addressList.setName(name);
        }
        if (group != null && !"".equals(group)) {
            addressList.setGroup(group);
        }
        if (imgUrl != null && !"".equals(imgUrl)) {
            addressList.setImgUrl(imgUrl);
        }
        if (loginId != null && !"".equals(loginId)) {
            addressList.setLoginId(loginId);
        }
        if (place != null && !"".equals(place)) {
            addressList.setPlace(place);
        }
        if (area != null && !"".equals(area)) {
            addressList.setArea(Integer.parseInt(area));
        }
        addressList.setId(id);
        //addressList.setCreateTime(new Date());
        return JSONObject.toJSON(addressListService.update(addressList) == 1 ? KitUtil.returnMap("200", StaticFinalVar.UPDATE_OK) : KitUtil.returnMap("101", StaticFinalVar.UPDATE_ERR));
    }

    /**
     * 删除
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    @ResponseBody
    public Object del(HttpServletRequest request) {
        log.info("通讯录 》 删除");
        String id = request.getParameter("id");
        return addressListService.delete(id) > 0 ? KitUtil.returnMap("200", StaticFinalVar.DEL_OK) : KitUtil.returnMap("101", StaticFinalVar.DEL_ERR);
    }

    /**
     * 图片上传接口 -- 用于layui
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/export", method = RequestMethod.POST)
    @ResponseBody
    public Object exportAddress(HttpServletRequest request) throws Exception {
        List<AddressList> list = addressListService.selectAllAddressList("");
        // 创建excel
        HSSFWorkbook wk = new HSSFWorkbook();
        // 创建一张工作表
        HSSFSheet sheet = wk.createSheet();
        // 设置列宽
        //sheet.setColumnWidth(0, 5000);
        // 创建第一行
        HSSFRow row = sheet.createRow(0);
        // 创建第一行的第一个单元格
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("序号");
        cell = row.createCell(1);
        cell.setCellValue("姓名");
        cell = row.createCell(2);
        cell.setCellValue("部门");
        cell = row.createCell(3);
        cell.setCellValue("工号");
        cell = row.createCell(4);
        cell.setCellValue("分机号");
        cell = row.createCell(5);
        cell.setCellValue("所在地");
        // 想单元格写值
        for (int i = 0; i < list.size(); i++) {
            AddressList addressList = list.get(i);
            row = sheet.createRow(i+1);
            cell = row.createCell(0);
            cell.setCellValue(i+1);
            cell = row.createCell(1);
            cell.setCellValue(addressList.getName());
            cell = row.createCell(2);
            cell.setCellValue(addressList.getGroup());
            cell = row.createCell(3);
            cell.setCellValue(addressList.getLoginId());
            cell = row.createCell(4);
            cell.setCellValue(addressList.getPlace());
            cell = row.createCell(5);
            String area = "";
            if(addressList.getArea()== 1){
                area = "北京";
            }else if(addressList.getArea()== 2){
                area = "上海";
            }
            cell.setCellValue(area);
        }
        // 保存到本地
        wk.write(new FileOutputStream(new File(servletContext.getRealPath("") + "/uplodefiles/通讯录.xls")));
        // 关闭工作薄
        wk.close();

        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> map1 = new HashMap<String, Object>();
        // 保存前台传来的缩略图
        map.put("code", 200);
        map.put("msg", "");
        return JSONObject.toJSON(map);
    }

    /**
     * 图片上传接口 -- 用于layui
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @ResponseBody
    public Object importAddress(HttpServletRequest request) throws Exception {
        //将HttpServletRequest转型为MultipartHttpServletRequest，不转型获取不到文件名。
        MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request;
        //获得文件
        MultipartFile file = mrequest.getFile("file");
        //获取输入流
        InputStream in = file.getInputStream();
        HSSFWorkbook wk = new HSSFWorkbook(in);
        HSSFCell cell=null;
        int cellType;
        String result=null;
        //数据格式
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //List<String> list=new ArrayList<String>(); //将导入人员姓名存入list中，方便前台显示！
        List<AddressList> list=new ArrayList<AddressList>();
        System.out.println("wk.getNumberOfSheets()==="+wk.getNumberOfSheets());
        for(int SheetNum=0;SheetNum<wk.getNumberOfSheets();SheetNum++){
            //获取excel表格中的sheet页
            HSSFSheet hssfsheet =wk.getSheetAt(SheetNum);
            if(hssfsheet==null){
                continue;
            }else{
                for(int rowNum=1;rowNum<=hssfsheet.getLastRowNum();rowNum++){
                    //创建一个行对象。
                    HSSFRow row=hssfsheet.getRow(rowNum);
                    for(int i=0;i<row.getLastCellNum();i++){
                    	row.getCell(i).setCellType(CellType.STRING);
					}
                    //实体对象
                    if(row==null){
                        continue;
                    }else{
                        try{
                            //一般下标是从0开始，但是excel表格第一行都是标题，不用读进来，所以从下标1开始。
                            //replaceAll(" ","")；去除姓名中的空格。
                            AddressList addressList = new AddressList();
                            addressList.setName(row.getCell(1).getStringCellValue());
                            addressList.setGroup(row.getCell(2).getStringCellValue());
                            addressList.setLoginId(row.getCell(3).getStringCellValue());
                            addressList.setPlace(row.getCell(4).getStringCellValue());
                            String areaStr = row.getCell(5).getStringCellValue();
                            Integer area = null;
                            if("北京".equals(areaStr)){
                                area = 1;
                            }else if("上海".equals(areaStr)){
                            }
                            addressList.setArea(area);
                            addressList.setCreateTime(new Date());
                            addressList.setId(KitUtil.uuid());
                        //将插入的一条信息的姓名放到list返回前台提示
                            list.add(addressList);
                        //插入一条人员信息，insertOne()是另外一个方法。
                        }catch (Exception e) {
                        	e.printStackTrace();
                            String msg="导入excel表格格式有问题，请确认后重试！";
                            Map<String, Object> map = new HashMap<String, Object>();
                            // 保存前台传来的缩略图
                            map.put("code", 500);
                            map.put("msg", msg);
                            return JSONObject.toJSON(map);
                        }
                    }
                }
            }
        }
        // 保存到本地
        for(AddressList addressList:list){
            addressListService.save(addressList);
        }
        // 关闭工作薄
        wk.close();

        Map<String, Object> map = new HashMap<String, Object>();
        // 保存前台传来的缩略图
        map.put("code", 0);
        map.put("msg", "通讯录excel导入成功");
        return JSONObject.toJSON(map);
    }
}
